package com.example.xx.config;

import com.example.xx.util.Code;
import com.example.xx.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 这个类用来处理没有登录的请求
 * 会相应给客户端一个未登录的json数据
 * @author ：jyj
 * @date ：Created in 2020/9/27
 */
@Component
public class NoLoginconfig implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        System.out.println("未登录或者登录过期");
        // 响应json数据给前端
        httpServletResponse.setContentType("application/json;charset=utf-8");
        // 封装响应数据
        Result result = new Result(Code.NO_LOGIN,"未登录或者登录过期");
        // 将响应数据转换为json格式
        ObjectMapper mapper = new ObjectMapper();
        // 将响应数据转换为json格式
        String s = mapper.writeValueAsString(result);
        // 响应给前端 并且结束请求
        httpServletResponse.getWriter().write(s);
        System.out.println(s);
        // 打印异常信息
        e.printStackTrace();
    }
}
